package com.dissertation.utils;

import com.dissertation.model.MongodbBaseModel;
import com.dissertation.model.auth.Role;
import com.dissertation.model.auth.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

import java.util.Optional;
import java.util.Set;

/**
 * Created by jsh3 on 17-12-3.
 */
public class AuthUtil {


    public static Optional<User> getUser() {
        Subject subject = SecurityUtils.getSubject();
        return Optional.ofNullable( (User) subject.getPrincipal() );
    }


    public static String getId() {
        return getUser().map( MongodbBaseModel::getId ).orElseThrow( () -> new RuntimeException( "对不起请登录" ) );
    }

    public static String getUsername() {
        return getUser().map( MongodbBaseModel::getUniqueName ).orElseThrow( () -> new RuntimeException( "对不起请登录" ) );
    }

    public static String getPassword() {
        return getUser().map( User::getPassword ).orElseThrow( () -> new RuntimeException( "对不起请登录" ) );
    }


    public static Set<Role> getRoles() {
        return getUser().map( User::getRole ).orElseThrow( () -> new RuntimeException( "对不起请登录" ) );
    }
}
